/**
 * 
 */
package com.txby.platformCore.component.util;

import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.jck.tools.ChkUtil;
import com.jck.tools.HttpToolUtil;
import com.tencent.xinge.ClickAction;
import com.tencent.xinge.Message;
import com.tencent.xinge.Style;
import com.tencent.xinge.TimeInterval;
import com.tencent.xinge.XingeApp;
import com.txby.platformCore.data.CommonXGRetunInfo;

/**
 * @author Administrator
 *
 */
public class XGPushUtil {
	private static XingeApp xinge;
	private static Message message1;
	private static Message message2;
	private static long accessId = 0;
	private static String secretKey = "";
	private static String title = "点餐提醒";
	private static String content = "尊敬的${name}患者：为了你的正常就餐,午餐请在10点前向工作人员预订。";
	private static String mealRemind = "尊敬的${name}患者：为了你的正常就餐,午餐请在10点前向工作人员预订。";
	private static String medicineRemind = "尊敬的${name}患者：为了你的身体健康,请遵照医嘱按时吃药。";
	private static String activityRemind = "尊敬的${name}患者：为了你的身体健康,请遵照医嘱按时进行康复活动。";
	private static String token = "";
	private static Map<Integer,Object>  customeParam =new HashMap();
//	private static Integer remindType=0;
    public static  XGPushUtil getNewInstance(long accessId, String secretKey){
    	xinge = new XingeApp(accessId, secretKey);
    	customeParam.put(0, "点餐提醒");
    	customeParam.put(1, "吃药提醒");
    	customeParam.put(2, "康复活动提醒");
    	return new XGPushUtil(accessId,secretKey);
    }
    
    private XGPushUtil(){
    
    }
    private XGPushUtil(long accessId, String secretKey){
    	this.accessId=accessId;
    	this.secretKey=secretKey;
    }
    
    public static void main(String[] args) {
    	System.out.println("我测试");
		token = "98909e7bd41de2fc42dd9a638435520000983ccd";
		accessId = 2100267178;
		secretKey = "3068da41c501f821e70300851ad5ab40";
		XGPushUtil xu=XGPushUtil.getNewInstance(accessId, secretKey);
//		CommonXGRetunInfo result=xg.pushSingleDeviceCustomMessage(token, title, content, 1);
		
		secretKey="941625866b31867cbff1b764cc0f91e7";
		token = "2b193b833c6073d943f8bde610cbf583057fbd09";
		accessId = 2100267633;
		
		xu=XGPushUtil.getNewInstance(accessId, secretKey);
		Map<Integer,String> callMap=new HashMap(){{
			put(0, "紧急呼叫");
			put(1, "换水呼叫");
			put(2, "普通呼叫");
		}};
		
		int callType=1;
		//呼叫护士端的类型字段
		System.out.println("呼叫护士端的类型字段");
		Map m=new HashMap();
		Map custom=new HashMap();
		Map data=new HashMap();
		m.put("callType", callType);
		m.put("discription",callMap.get(callType));
		m.put("msgId", 33);
		data.put("bedNO", "B01");
		data.put("sickAreaName", "十病区");
		data.put("sickName","");
		//查询患者信息
		m.put("data", data);
		custom.put("data", m);
		System.out.println(JSON.toJSON(custom));
		CommonXGRetunInfo result=xu.pushSingleDeviceCustomMessage(token,callMap.get(callType)+":推送护士端的类型字段", "此是消息内容推送护士端的类型字段", custom, 1);
//		CommonXGRetunInfo result=xu.pushSingleDeviceCustomMessage(token, title, content, 1);
		System.out.println(result.toString());
		
		//护士端响应患者端的类型字段
		System.out.println("护士端响应患者端的类型字段");
		
	  m=new HashMap();
	  custom=new HashMap();
		  data=new HashMap();
		m.put("respondType", callType);
		m.put("discription", callMap.get(callType));
		m.put("msgId", 33);
		//查询信息
//		m.put("data", data);
		custom.put("data", m);
		
		System.out.println(JSON.toJSON(custom));
		
		CommonXGRetunInfo info=xu.pushSingleDeviceCustomMessage(token, callMap.get(callType)+":响应患者端的类型字段", "此是消息内容响应患者端的类型字段",custom, 1);
		System.out.println(result.toString());
		
		//
	}
    /**
     * 单个设备下发自定义消息
     * @param token 设备token 必填
     * @param message 自定义消息 必填
     * @return
     */
	public CommonXGRetunInfo pushSingleDeviceCustomMessage(String token,Message message) {
		JSONObject ret = xinge.pushSingleDevice(token, message);
		CommonXGRetunInfo result=new CommonXGRetunInfo();
		result.setRet_code(ret.getInt("ret_code"));
		if(ret.has("err_msg")) result.setErr_msg(ret.getString("err_msg"));
		if(ret.has("result")) result.setResult(ret.getString("result"));
		return result;

	}
	/**
	 * @param token 设备token 必填
	 * @param title 标题必填
	 * @param content 内容必填
	 * @param custom 自定义参数可选
	 * @param url   链接url可选
	 * @param msgType 1通知消息，2透传消息
	 * @return
	 */
	public CommonXGRetunInfo pushSingleDeviceCustomMessage(String token,String title,String content,Map<String, Object> custom ,String url,int msgType) {
		message1 = new Message();
		message1.setType(msgType);
		Style style = new Style(1);
		style = new Style(3, 1, 0, 1, 0);
		message1.setTitle(title);
		message1.setContent(content);
		message1.setStyle(style);
		if(!ChkUtil.isEmptyAllObject(url)){
			ClickAction action = new ClickAction();
			action.setActionType(ClickAction.TYPE_URL);
			action.setUrl(url);
			message1.setAction(action);
		}
		if(!ChkUtil.isEmptyAllObject(custom)){
			message1.setCustom(custom);
			
		}
		JSONObject ret = xinge.pushSingleDevice(token, message1);
		CommonXGRetunInfo result=new CommonXGRetunInfo();
		result.setRet_code(ret.getInt("ret_code"));
		if(ret.has("err_msg")) result.setErr_msg(ret.getString("err_msg"));
		if(ret.has("result")) result.setResult(ret.getString("result"));
		return result;
		
	}
	/**
	 * @param token 设备token 必填
	 * @param title 标题必填
	 * @param content 内容必填
	 * @param custom 自定义参数可选
	 * @param msgType 1通知消息，2透传消息
	 * @return
	 */
	public CommonXGRetunInfo pushSingleDeviceCustomMessage(String token,String title,String content,Map<String, Object> custom ,int msgType) {
		message1 = new Message();
		message1.setType(msgType);
		Style style = new Style(1);
		style = new Style(3, 1, 0, 1, 0);
		message1.setTitle(title);
		message1.setContent(content);
		message1.setStyle(style);
		if(!ChkUtil.isEmptyAllObject(custom)){
			message1.setCustom(custom);
			
		}
		JSONObject ret = xinge.pushSingleDevice(token, message1);
		CommonXGRetunInfo result=new CommonXGRetunInfo();
		result.setRet_code(ret.getInt("ret_code"));
		if(ret.has("err_msg")) result.setErr_msg(ret.getString("err_msg"));
		if(ret.has("result")) result.setResult(ret.getString("result"));
		return result;
		
	}
	/**
	 * @param token 设备token必填
	 * @param title 标题必填
	 * @param content 内容必填
	 * @param msgType 1通知消息，2透传消息
	 * @param typeRemind   提醒类型	customeParam.put(0, "点餐提醒");
    	customeParam.put(1, "吃药提醒");
    	customeParam.put(2, "康复活动提醒");
	 * @return
	 */
	public CommonXGRetunInfo pushSingleDeviceCustomMessage(String token,String title,String content,int msgType,Integer remindType) {
		message1 = new Message();
		message1.setType(msgType);
		Style style = new Style(1);
		style = new Style(3, 1, 0, 1, 0);
		message1.setTitle(title);
		message1.setContent(content);
		message1.setStyle(style);
		Map<String, Object> custom=new HashMap();
		if(!ChkUtil.isEmptyAllObject(remindType)&&customeParam.get(remindType)!=null){
			Map m=new HashMap();
			m.put("remindType", remindType);
			m.put("discription", customeParam.get(remindType));
			custom.put("data", m);
			message1.setCustom(custom);
		}
		JSONObject ret = xinge.pushSingleDevice(token, message1);
		CommonXGRetunInfo result=new CommonXGRetunInfo();
		result.setRet_code(ret.getInt("ret_code"));
		if(ret.has("err_msg")) result.setErr_msg(ret.getString("err_msg"));
		if(ret.has("result")) result.setResult(ret.getString("result"));
		return result;
		
	}
	/**
	 * @param token 设备token必填
	 * @param title 标题必填
	 * @param content 内容必填
	 * @param msgType 1通知消息，2透传消息
	 * @return
	 */
	public CommonXGRetunInfo pushSingleDeviceCustomMessage(String token,String title,String content,int msgType) {
		message1 = new Message();
		message1.setType(msgType);
		Style style = new Style(1);
		style = new Style(3, 1, 0, 1, 0);
		message1.setTitle(title);
		message1.setContent(content);
		message1.setStyle(style);
		Map<String, Object> custom=new HashMap();
	/*	if(!ChkUtil.isEmptyAllObject(typeRemind)&&customeParam.get(typeRemind)!=null){
			m.put("remindType", remindType);
			m.put("discription", customeParam.get(remindType));
			custom.put("data", m);
		}*/
		JSONObject ret = xinge.pushSingleDevice(token, message1);
		CommonXGRetunInfo result=new CommonXGRetunInfo();
		result.setRet_code(ret.getInt("ret_code"));
		if(ret.has("err_msg")) result.setErr_msg(ret.getString("err_msg"));
		if(ret.has("result")) result.setResult(ret.getString("result"));
		return result;
		
	}
 

	@Before
	private void before() {
		/**
		 * 我测试
		 */
		System.out.println("我测试");
		token = "98909e7bd41de2fc42dd9a638435520000983ccd";
		accessId = 2100267178;
		secretKey = "3068da41c501f821e70300851ad5ab40";
		xinge = new XingeApp(accessId, secretKey);

		message1 = new Message();
		message1.setType(Message.TYPE_NOTIFICATION);
		Style style = new Style(1);
		style = new Style(3, 1, 0, 1, 0);
		ClickAction action = new ClickAction();
		action.setActionType(ClickAction.TYPE_URL);
		action.setUrl("http://xg.qq.com");
		Map<String, Object> custom = new HashMap<String, Object>();
		custom.put("key1", "value1");
		custom.put("key2", 2);
		message1.setTitle("title");
		message1.setContent("大小");
		message1.setStyle(style);
		message1.setAction(action);
		message1.setCustom(custom);
		//按时间段
		TimeInterval acceptTime1 = new TimeInterval(0, 0, 23, 59);
		message1.addAcceptTime(acceptTime1);

		message2 = new Message();
		message2.setType(Message.TYPE_NOTIFICATION);
		message2.setTitle("title");
		message2.setContent("通知点击执行Intent测试");
		style = new Style(1);
		action = new ClickAction();
		action.setActionType(ClickAction.TYPE_INTENT);
		action.setIntent("intent:10086#Intent;scheme=tel;action=android.intent.action.DIAL;S.key=value;end");
		message2.setStyle(style);
		message2.setAction(action);
	}
	


	// 单个设备下发透传消息
	@Test
	private void demoPushSingleDeviceMessage() {
		Message message = new Message();
		// 自定义消息customContent
		Map custom = new HashMap() {
			{
				List data = new ArrayList<>();
				Map temp = new HashMap();
				temp.put("type", 0);
				temp.put("title", "点餐提醒消息");
				data.add(temp);
				temp = new HashMap();
				temp.put("type", 1);
				temp.put("title", "吃药提醒消息");
				data.add(temp);
				temp = new HashMap();
				temp.put("type", 2);
				temp.put("title", "康复活动提醒提醒消息");
				data.add(temp);
				put("data", data);

			}
		};
		message.setCustom(custom);
		message.setTitle(title);
		message.setContent(content);
		message.setType(Message.TYPE_MESSAGE);
		message.setExpireTime(86400);
		JSONObject ret = xinge.pushSingleDevice(token, message);
		System.out.println(ret);

	}



	// 单个设备下发通知Intent
	// setIntent()的内容需要使用intent.toUri(Intent.URI_INTENT_SCHEME)方法来得到序列化后的Intent(自定义参数也包含在Intent内）
	// 终端收到后可通过intent.parseUri()来反序列化得到Intent
	@Test
	private void demoPushSingleDeviceNotificationIntent() {
		JSONObject ret = xinge.pushSingleDevice(token, message2);
		System.out.println(ret);

	}

	@Test
	private void queryInfoOfToken() {
		String url = "http://openapi.xg.qq.com/v2/application/get_app_token_info";
		Map<String, String> params = new HashMap();
		/* 719:939 */ params.put("access_id", String.valueOf(accessId));
		/* 720:940 */ params.put("device_token", token);
		/* 721:941 */ params.put("timestamp", Long.valueOf(System.currentTimeMillis() / 1000L).toString());
		String ret = "";
		/* 109:102 */ JSONObject jsonRet = null;
		/* 110:103 */ String sign = generateSign("POST", url, params);
		/* 114:105 */ params.put("sign", sign);
		String method = "POST";
		 String content=HttpToolUtil.getInstance().sendHttpCustom(url, method, params, false, null);
		 System.out.println(content);

	}

	public String generateSign(String method, String url, Map<String, String> params) {
		List<Map.Entry<String, Object>> paramList = new ArrayList(params.entrySet());

		Collections.sort(paramList, new Comparator<Map.Entry<String, Object>>() {
			public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
				return ((String) o1.getKey()).toString().compareTo((String) o2.getKey());
			}
		});
		String paramStr = "";
		String md5Str = "";
		for (Map.Entry<String, Object> entry : paramList) {
			paramStr = paramStr + (String) entry.getKey() + "=" + entry.getValue().toString();
		}
		try {
			URL u = new URL(url);
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			String s = method + u.getHost() + u.getPath() + paramStr + secretKey;
			byte[] bArr = s.getBytes("UTF-8");
			byte[] md5Value = md5.digest(bArr);
			BigInteger bigInt = new BigInteger(1, md5Value);
			md5Str = bigInt.toString(16);
			while (md5Str.length() < 32) {
				md5Str = "0" + md5Str;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return md5Str;
	}

}
